<template>
  <div class="favorable">
      <div class="header">
      <carnt-header :text="'分时优惠'" :backPage="'spray'"></carnt-header>
      <div class="navBar">
        <div class="allItem">
          <div class="item" v-for="(item,index) in pages" :class="{active:(index-1)==currentIndex}" @click="selectTime($event,index,item.time,item.year)">
            <div class="itemBox">
              <p>{{item.time}}</p>
              <p>{{item.week}}</p>
            </div>
          </div>
        </div>
      </div>
      </div>
      <div class="allStore">
          <div class="Store" v-for="items in allfenshiM"><!-- 循环4S店 -->
            <div class="storeMess" @click="go4SshopDetail(items)">
              <img :src="items.SHOP_PHOTO" />
              <div class="storeIntro">
                <h2>{{items.SHOP_NAME}}</h2>
                <p class="storeAddress">{{items.ADDRESS}}</p>
                <p class="storePrice"><em>&yen; </em>{{(Number(items.SPARY_TOTAL) - Number(items.PAINT_TOTAL)).toFixed(2)>=0?(Number(items.SPARY_TOTAL) - Number(items.PAINT_TOTAL)).toFixed(2):0}}<!-- ??? .<em>00</em>--></p>
              </div>
              <div class="distance">
                {{distance(items.SHOP_COORD)}}km
              </div>
            </div>
            <ul>
              <li v-for="item in items.SCHEDULE_DATA"><!-- 循环下单时间 -->
                <div class="timeMes">
                  <p class="time">{{item.STARTTIME}}-{{item.ENDTIME}}</p>
                  <p class="stock" v-if="item.SCHEDULE_PRICE">准时到店可获得<span>{{item.SCHEDULE_PRICE}}</span>元工时劵</p>
                </div>
                <div class="downOrder">
                  <!-- <router-link to="/pay"> -->
                    <button class="past" v-if="item.ENDTIME_LONG <= new Date().getTime()">已过期</button>
                    <!-- Order（店id，项目id 支付的时候传这个id，店名，选中喷漆部位数组，优惠金额） -->
                    <button @click="Order(items.COMP_ID, item.SCHEDULE_DETAIL_ID, items.SHOP_NAME, items.POSITION_DATA, items.PAINT_TOTAL,items.SPARY_TOTAL)" v-if="item.ENDTIME_LONG>new Date().getTime()">下单</button>
                  <!-- </router-link> -->
                </div>           
              </li> 
            </ul>
          </div>
      </div>
  </div>
</template>

<script>
import carntHeader from './commonParts/CarntHeader';
import { MessageBox ,Indicator,Toast } from 'mint-ui';
import { getCookie, setCookie } from '../assets/js/cookie';
export default {
  name: 'Schedule',
  // 数据
  data () {
    return {
      msg: '分时优惠',
      pages: [],
      currentIndex: 0,
      allfenshiM: [],//所有分时优惠的店家信息
      orderTime: "",   //下单时间（2017-4-22）
      allActInfo: '' //喷漆页传递的所有活动信息
    }
  },
  // 创建
  created () {
    // 分时优惠顶部的时间队列的产生，默认生产六天的
    var date=new Date();
    for(var i=-1;i<5;i++){
      var newDate=new Date(date.getTime()+i*24*60*60*1000);
      let obj={};
      let weekNum=newDate.getDay();
      let week;

      switch(weekNum){
        case 1:week="星期一"; break;
        case 2:week="星期二"; break;
        case 3:week="星期三"; break;
        case 4:week="星期四"; break;
        case 5:week="星期五"; break;
        case 6:week="星期六"; break;
        case 0:week="星期日"; break;
      }
      if(i==0){
        obj.week="今天";
      }else{
        obj.week=week;
      }
      obj.year=newDate.getFullYear();
      let month=newDate.getMonth()+1;
      month=month>=10?month:"0"+month;
      let day=newDate.getDate();
      day=day>=10?day:"0"+day;
      obj.time=month+"-"+day;
      this.pages.push(obj);
    }
    // 今天的时间
    let nowYear=date.getFullYear();
    let nowMonth=date.getMonth()+1;
    nowMonth=nowMonth>=10?nowMonth:"0"+nowMonth;
    let nowDay=date.getDate();
    nowDay=nowDay>=10?nowDay:"0"+nowDay;
    // 获取spray传过来的参数
    let carbrand=this.$store.state.defaultCatAllInfo.BRAND;
    let carset=this.$store.state.defaultCatAllInfo.SET;
    let city=this.$store.state.cityName;
    this.getData(nowYear,nowMonth,nowDay);
    this.orderTime=nowYear+"-"+nowMonth+"-"+nowDay;

    // 2017-5-23 新增
    this.allActInfo = JSON.parse( localStorage.getItem('allActInfo') );
    // console.log('allActInfo', JSON.parse( localStorage.getItem('allActInfo') ))
    // 显示加载中
    Indicator.open();
  },
  // 渲染
  mounted () {
    
  },
  // 销毁前
  beforeDestory () {

  },
  // 计算
  computed: {

  },
  // 方法
  methods: {
    //当点击顶部时间队列最后一个或者第一个的时候，就往时间队列中添加前一天或者后一天的时间
    selectTime(event,index,time,year){
      Indicator.open();
      this.orderTime=year+"-"+time;
      console.log(event.currentTarget);
      this.currentIndex=index-1;
      let times=new Date(year+"-"+time);
      console.log()
      // 当点击到最后一个时自动向数组中添加后一天，同时删除数组中的第一个元素
      if(index>=5){
        var addTime=new Date(times.getTime()+1*24*60*60*1000);
        let obj={};
        let weekNum=addTime.getDay();
        let week;
        this.currentIndex--;
        switch(weekNum){
          case 1:week="星期一"; break;
          case 2:week="星期二"; break;
          case 3:week="星期三"; break;
          case 4:week="星期四"; break;
          case 5:week="星期五"; break;
          case 6:week="星期六"; break;
          case 0:week="星期日"; break;
        }
          obj.week=week;
          obj.year=addTime.getFullYear();
          let month=addTime.getMonth()+1;
          month=month>=10?month:"0"+month;
          let day=addTime.getDate();
          day=day>=10?day:"0"+day;
          obj.time=month+"-"+day;
          this.pages.push(obj);
          this.pages.shift();
          if((year==new Date().getFullYear())&&(time.split("-")[0]==(new Date().getMonth()+1))&&(time.split("-")[1]==new Date().getDate())){
            this.pages[index-1].week="今天";
          }
        }
        // 当点击第一个是自动向数组的头部添加当前天的前一天，同时删除数组中的最后一个元素
        if(index<=0){
          var subtractTime=new Date(times.getTime()-1*24*60*60*1000);
          let obj={};
          let weekNum=subtractTime.getDay();
          let week;
          this.currentIndex++;
          switch(weekNum){
            case 1:week="星期一"; break;
            case 2:week="星期二"; break;
            case 3:week="星期三"; break;
            case 4:week="星期四"; break;
            case 5:week="星期五"; break;
            case 6:week="星期六"; break;
            case 0:week="星期日"; break;
          }
          obj.week=week;
          obj.year=subtractTime.getFullYear();
          let month=subtractTime.getMonth()+1;
          month=month>=10?month:"0"+month;
          let day=subtractTime.getDate();
          day=day>=10?day:"0"+day;
          obj.time=month+"-"+day;
          this.pages.unshift(obj);
          this.pages.pop();
          if((year==new Date().getFullYear())&&(time.split("-")[0]==(new Date().getMonth()+1))&&(time.split("-")[1]==new Date().getDate())){
            this.pages[index+1].week="今天";
          }
        }
        //点击别的时间是去后台获取分时优惠的店家信息
        let carbrand=this.$store.state.defaultCatAllInfo.BRAND;
        let carset=this.$store.state.defaultCatAllInfo.SET;
        let city=this.$store.state.cityName;
        // 去请求
        this.getData(year,time.split("-")[0],time.split("-")[1]);
    },
    getData(year,month,day){
      var fenPort=this.$store.state.ip+"/CARNT/sprayWeb/getSparySchedule";
      let _this=this;
      // 选择出store存储的钣喷的车的信息和钣喷的区域、城市
      let defaultCatAllInfo=JSON.parse(localStorage.getItem("defaultCatAllInfo"));
      let positions=JSON.parse(localStorage.getItem("PartsOfChoose")).concat(JSON.parse(localStorage.getItem("PartsOfChooseW")));//钣喷位置
      
      let carbrand=defaultCatAllInfo.BRAND;  //车辆名
      let carset=defaultCatAllInfo.SET;      //车辆类型
      let city=localStorage.getItem("cityName");   //城市名
      let newPosition=[];
      for(var i=0;i<positions.length;i++){
        let str="'"+positions[i]+"'";
        newPosition.push(str);
      }
      let position=newPosition.join(",");    //后台需要钣喷位置格式
      //向后台请求钣喷分时优惠
      this.$http.post(fenPort,{
        YEAR:year,
        MONTH:month,
        DAY:day,
        CATEGORY:2,
        CAR_BRAND:carbrand,
        CAR_SET:carset,
        CITY:city,
        POSITION:position
      },{emulateJSON:true}).then(function(res){
        if(res.body.STATUS_CODE==1){
            Indicator.close();
            if(res.body.RESULT_DATA.length==0){
                Toast({
                  message: '暂无数据',
                  position: 'middle',
                  duration: 2000
                });
                return;
            }else{
              _this.allfenshiM=res.body.RESULT_DATA;
            }
            
            
        }
      },function(){
      })
    },
    distance(str){
      let lngs=str.split(",")[0];//店家的经度
      let lats=str.split(",")[1];//店家的纬度
      // 获取store设置的你的当前经纬度(即用户当前的位置)
      let lgnLat=localStorage.getItem("localLngLat");
      let lng=lgnLat.split(",")[0];
      let lat=lgnLat.split(",")[1];
      // 百度地图API功能
      var map = new BMap.Map();
      //初始化地图,设置城市和地图级别。
      var pointA = new BMap.Point(lng,lat);  // 创建点坐标A--自己地址
      var pointB = new BMap.Point(lngs,lats);  // 创建点坐标B--店家位置
      return ((map.getDistance(pointA,pointB))/1000).toFixed(2);
    },
    Order(compId,scheduleId,shopName,position,paint_total,SPARY_TOTAL){
      // Order（店id，项目id 支付的时候传这个id，店名，选中喷漆部位数组，优惠金额）
      // 是否登录 
      let paintTotal='';
      if(paint_total>SPARY_TOTAL){
         paintTotal=SPARY_TOTAL;
      }else{
         paintTotal=paint_total;
      }
      if ( getCookie("loginkey") && getCookie("userName") ) {

          let orderMess = {};//用来保存下单所需要的信息
          orderMess.USER_ID = getCookie("loginkey");//用户ID
          orderMess.COMP_ID = compId;    //下单店家编号
          orderMess.SCHEDULE_DETAIL_ID = scheduleId;  //分时编号
          orderMess.shopName = shopName;//店家名称
          orderMess.orderTime = this.orderTime;//下单时间
          orderMess.SERV_PARAMS = position;//选择钣喷部位信息数组
          orderMess.paint_total = paintTotal;// 这家店优惠总价

          // 有开活动！且没有选择全车钣喷！的话---跳转前调用/sprayWeb/createSprayItem接口替换部位id
          let hasAll = JSON.parse(localStorage.getItem("PartsOfChoose")).indexOf('ALL') == -1;// 车身部位数组是否存在'ALL'  true不存在 false存在
          // console.log(hasAll)
          
          // 不是全车钣喷 且开活动走createSprayItem接口替换部位id
          if (hasAll) {
            if ( this.allActInfo.HAS_COMBINATION_SPRAY != 0 ) {
              let serv_ids = '';
              for (var i = 0; i < orderMess.SERV_PARAMS.length; i++) {
                serv_ids += orderMess.SERV_PARAMS[i].SERV_DETAIL_ID + ',';
              }
              serv_ids = serv_ids.slice(0,-1);

              let createSprayItem = {
                userid: orderMess.USER_ID,
                COMP_ID: orderMess.COMP_ID,
                HAS_COMBINATION_SPRAY: this.allActInfo.HAS_COMBINATION_SPRAY,// 组合优惠模式 1 2 3 4 
                HAS_SPRAY_PRICE:this.allActInfo.HAS_SPRAY_PRICE,//满减优惠中的首付多少钱
                COMBINATION_SERV_IDS:serv_ids // 所有部位id 
              }
              console.log(createSprayItem);
              this.$http.post( this.$store.state.ip+'/CARNT/sprayWeb/createSprayItem',
                createSprayItem
                ,{emulateJSON:true}
              ).then(function(res){
                var data = res.body;
                var idArr = data.NEW_COMBINATION_SERV_IDS.split(',');// 转数组
                // 循环替换ID
                for (var i = 0; i < orderMess.SERV_PARAMS.length; i++) {
                  orderMess.SERV_PARAMS[i].SERV_DETAIL_ID = idArr[i]
                }


                // 将支付页面所需要的数据存储在localStorage中
                localStorage.setItem("orderMessage",JSON.stringify(orderMess));
                // 清除已生成支付订单信息（已生成订单->取消支付->后退->下单）
                sessionStorage.setItem('WX_order_info','');
                // 跳转
                // this.$router.push("pay");
                location.href = this.$store.state.ip + '/CARNT/jsp/pay/index.html?#/pay';
              })

            } else {
              // 将支付页面所需要的数据存储在localStorage中
              localStorage.setItem("orderMessage",JSON.stringify(orderMess));
              // 清除已生成支付订单信息（已生成订单->取消支付->后退->下单）
              sessionStorage.setItem('WX_order_info','');
              // 跳转
              // this.$router.push("pay");
              location.href = this.$store.state.ip + '/CARNT/jsp/pay/index.html?#/pay';
            }
          } else {
            // 选择了全车钣喷
            // 全车翻新活动开启替换新的serverId
            let actInfo = JSON.parse(localStorage.getItem('allActInfo'));
            if (position.length == 1 && position[0].POSITION == 'ALL' && actInfo.HAS_REFURBISHED_DIS == '1') {
              let changeServId = this.$store.state.ip+"/CARNT/sprayWeb/createSprayItem";
              this.$http.post(changeServId,{
                COMP_ID: compId, // 商店编号
                SERV_ID: position[0].SERV_DETAIL_ID, // 部位id
                REFURBISHED_DIS:  actInfo.REFURBISHED_DIS // 折扣率
              },{emulateJSON:true}).then((res) => {
                if(res.body.STATUS_CODE == 1){
                  console.log(res.body.NEW_SERV_ID)
                  orderMess.SERV_PARAMS[0].SERV_DETAIL_ID = res.body.NEW_SERV_ID // 替换全车翻新服务id
                  // 将支付页面所需要的数据存储在localStorage中
                  localStorage.setItem("orderMessage",JSON.stringify(orderMess));
                  // 清除已生成支付订单信息（已生成订单->取消支付->后退->下单）
                  sessionStorage.setItem('WX_order_info','');
                  // 跳转
                  location.href = this.$store.state.ip + '/CARNT/jsp/pay/index.html?#/pay';
                }
              },(err) =>{
              })
            } else {
              // 将支付页面所需要的数据存储在localStorage中
              localStorage.setItem("orderMessage",JSON.stringify(orderMess));
              // 清除已生成支付订单信息（已生成订单->取消支付->后退->下单）
              sessionStorage.setItem('WX_order_info','');
              // 跳转
              location.href = this.$store.state.ip + '/CARNT/jsp/pay/index.html?#/pay';
            }
          }


      }else{
          MessageBox('提示', '请先登录').then(action => {
            location.href = this.$store.state.ip + "/CARNT/jsp/pay/indexM.html#/login";
          });  
     }
    },
    // 去4S店详情页
    go4SshopDetail (item) {
      // 坐标
      const position = window.localStorage.getItem('localLngLat') || "113.93808046029,22.554739164041"
      location.href = "http://carnt.carnettong.com:8088/CARNT/jsp/pay/indexM.html#/storeDetail/" + item.COMP_ID + "?coordinate=" + position
    }
  },
  // 子组件
  components: {
    carntHeader
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h1, h2 {
  font-weight: normal;
  a{
    font-size:.16rem;
  }
}
ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 0.1rem;
}

a {
  color: #42b983;
}
.test{
  width:7.5rem;
  height:3rem;
  background:red;
  font-size:.5rem;
}
.favorable{
  width: 7.5rem;
  text-align: left;
  background: #ddd;
}
button{
  outline: medium;
}
 *{
    margin: 0;
    padding: 0;
  }
  a{
    text-decoration: none;
  }
  .navBar{
    background: #e42e3b;
    
    .allItem{
      width: 7rem;
      margin: 0 auto;
      height: 1.4rem;
      display: flex;
      overflow: hidden;
      flex-wrap:nowrap;
      padding: .2rem 0;
      text-align: center;
      color: #fff;
      font-size: .25rem;
      margin-top: -1px;
    .item{
      width: 1.14rem;
      height:1rem;
      line-height: .4rem;
      padding:.1rem 0;
      border-left: 1px solid rgba(255,255,255,.6);
      box-sizing: border-box;
    }
    .item:first-child{
      border-left: 0;
    }
    .active+.item{
      border-left: 0;
    }
    .active{
      width: 1.26rem;
      height:1.06rem;
      margin-top: -.15rem;
      line-height: .5rem;
      background: #fff;
      color: red;
      font-size: .3rem;
      font-weight: bold;
      border-radius: .2rem;
      border: .04rem solid #f0858d;
      box-sizing:content-box;
      //box-shadow: 0 0 40px #f0858d;
    }
    }
  }
 .header{
  position:fixed;
  top: 0;
 }
 .allStore{
    margin-top: 2.19rem;
 }
  .Store{
    
      background: white;
      border-bottom:.22rem solid #eee;
      //box-shadow: 0 0 10px #ddd;
      box-sizing: content-box;
  }
  .Store:last-child{
     border-bottom: 0;
  }
  .storeMess{
    display: flex;
    padding: .29rem .10rem .29rem .29rem;
    height: 1.85rem;
    box-sizing: border-box;
    border-bottom: 1px solid #EEEEEE;
  }
  .storeMess img{
    height: 1.26rem;
    width: 1.26rem;
    min-width: 1.26rem;
    border-radius: .08rem;
  }
  .storeMess .storeIntro{
    width:4.2rem;
    margin: 0 .2rem 0 .2rem;
  }
  .storeMess .storeIntro h2{
    font-size: .3rem;
    margin-bottom: .1rem;
    font-weight: bold;
    color: #000;
  }
  .storeMess .storeIntro p.storeAddress{
    font-size: .24rem;
    margin: .1rem 0;
    color: #666;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }
  .storeMess .storeIntro p.storePrice{
    color: #ec2121;
    font-size: .3rem;
    font-weight: bold;
    em{
      font-size: .23rem;
      font-weight: normal;
    }
  }
  .storeMess .distance{
    width: 1.19rem;
    text-align: right;
    line-height: 1.5rem;
    font-size: .27rem;
    color: #b7b5b5;
  }
  .Store ul li{
    display: flex;
    height: 1rem;
    border-bottom: 1px solid #EEEEEE;
  }
  .Store ul li .timeMes{
    width: 80%;
    padding-left: .2rem;
    line-height: .5rem;
  }
  .Store ul li .timeMes p:only-child{
    line-height: 1rem;
  }
  .Store ul li .timeMes .time{
    font-size: .32rem;
    color: #333;
  }
  .Store ul li .timeMes .stock{
    font-size: .22rem;
    color: #999;
    margin-top: -.1rem;
    span{
      color:#ec2121;
      font-size: .3rem;
    }
  }
  .Store ul li .downOrder{
    width: 20%;
    text-align: center;
    line-height: .5rem;
  }
  .Store ul li .downOrder button{
    color: #FFFFFF;
    background: red;
    border-radius: .1rem;
    width: 1.16rem;
    height: .58rem;
    margin-top: .21rem;
    border: 0;
    font-size: .28rem;
  }
  .Store ul li .downOrder .past{
    background: #ddd;
    color: #fff;
  }
</style>
